<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Jiannei\Response\Laravel\Support\Facades\Response;

class AuthController extends Controller
{
    // 登录
    public function login(Request $request){
        $data = $request->validate([
            'email' => 'required|email',
            'password' => 'required'
        ]);
    
        $user = User::where('email', $request->email)->first();
    
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'message' => ['账户或密码错误.']
            ], 404);
        }
        //创建API令牌 //获取令牌明文
        $token = $user->createToken('Zsite')->plainTextToken;

        $user->roles = ['superAdmin','admin'];
    
        $response = [
            'user' => $user,
            'token' => $token
        ];
    
        return Response::success($response,201);

    }

    /**
     * Register api
     *
     * @param  [string] name
     * @param  [string] email
     * @param  [string] password
     * @param  [string] password_confirmation
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'password_confirmation' => 'required|same:password',
        ]);

        if ($validator->fails()) {
            return response()->json(['error'=>$validator->errors()], 401);
        }

        $input = $request->all();

        $user = User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => Hash::make($input['password']),
        ]);

        //创建API令牌 //获取令牌明文
        $token = $user->createToken('Zsite')->plainTextToken;

        $response = [
            'user' => $user,
            'token' => $token
        ];

        return Response::success($response);
    }


    /**
     * Logout user (Revoke the token)
     *
     * @return [string] message
     */
    public function logout(Request $request)
    {
        // 撤销所有令牌...
        $request->user()->tokens()->delete();

        return Response::success('Successfully logged out');
    }

        /**
     * Get the authenticated User
     *
     * @return [json] user object
     */
    public function user(Request $request)
    {
        /**
         * 获取已认证的用户 https://learnku.com/docs/laravel/8.x/authentication/9381#26a12e
        */
        $user = $request->user();
        $user->roles = ['superAdmin','admin'];
        return Response::success($user);
    }

}
